package com.keepalive_kotlin.service

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import androidx.core.app.NotificationCompat
import com.keepalive_kotlin.R

/**
 * 保活服务类
 * 通过前台服务和持续通知来保持应用活跃
 */
class KeepAliveService : Service() {

    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        startForeground(NOTIFICATION_ID, createNotification())
        return START_STICKY // 服务被杀死后会尝试重启
    }

    override fun onBind(intent: Intent?): Nothing? {
        return null
    }

    override fun onDestroy() {
        super.onDestroy()
        stopForeground(true)
    }

    /**
     * 创建通知渠道（Android 8.0及以上）
     */
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                CHANNEL_NAME,
                NotificationManager.IMPORTANCE_LOW
            )
            channel.description = "应用保活服务通知"
            channel.enableLights(true)
            channel.lightColor = Color.BLUE
            channel.enableVibration(false)
            channel.setSound(null, null)

            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }

    /**
     * 创建前台服务通知
     */
    private fun createNotification(): Notification {
        val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationCompat.Builder(this, CHANNEL_ID)
        } else {
            NotificationCompat.Builder(this)
        }

        return builder
            .setContentTitle("应用保活服务")
            .setContentText("正在后台保持运行")
//            .setSmallIcon(android.R.drawable.ic_notification_overlay)
            .setOngoing(true) // 设置为持续通知
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .build()
    }

    companion object {
        const val NOTIFICATION_ID = 1001
        const val CHANNEL_ID = "keep_alive_channel"
        const val CHANNEL_NAME = "保活服务"
    }
}